package com.banciyuan.bcywebview.biz.main.mineinfo.sina;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.sns.UsersAPI;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbAuthListener;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.sina.weibo.sdk.auth.sso.SsoHandler;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.SinaUser;

/**
 * Created by squall on 2016/6/15.
 */
public class SinaFriendsActivity extends BaseActivity {

    private PullToRefreshListView refreshListView;
    private ListView mListView;
    private LinearLayout sina_container;
    private TextView sina_bind;
    private SinaFriendAdapter adapter;
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private RequestQueue queue;
    private List<SinaUser> slist = new ArrayList<>();
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private boolean isEnd = false;
    private boolean is_load = false;
    private SsoHandler mSsoHandler;
    private int offset;
    private int page;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sina_user);
        initArgs();
        initProgressbar();
        initActionbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(this);
        mSsoHandler = new SsoHandler(this);
    }

    @Override
    protected void initUi() {
        refreshListView = (PullToRefreshListView) findViewById(R.id.topic_refresh_lv);
        mListView = refreshListView.getRefreshableView();
        sina_container = (LinearLayout) findViewById(R.id.sina_bind).getParent();
        sina_bind = (TextView) findViewById(R.id.sina_bind);
    }

    @Override
    protected void initData() {
        is_load = true;
        List<BcyPair> paramsList = new ArrayList<>();
        String url = HttpUtils.BASE_URL + UserApi.getSinaFriend();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair("offset", String.valueOf(offset)));
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                try {
                    sina_container.setVisibility(View.GONE);
                    JSONObject jsonObject = new JSONObject(result);
                    int status = jsonObject.getInt("status");
                    if (status == 1) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        offset = data.getInt("next_offset");
                        Gson gson = new Gson();
                        List<SinaUser> temp = gson.fromJson(data.getString("users"), new TypeToken<List<SinaUser>>() {
                        }.getType());
                        if (offset == 0) {
                            isEnd = true;
                        }
                        dealJson(temp);
                    } else if (status == 2400) {
                        mProgressbarHelper.onSuccess();
                        sina_container.setVisibility(View.VISIBLE);
                        sina_bind.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                doweiboAuthor();
                            }
                        });
                    }
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                    refreshListView.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
                refreshListView.onRefreshComplete();
            }
        };
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, SinaFriendsActivity.this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(requestParam);
    }

    private void bindSina(final Oauth2AccessToken accessToken) throws Exception {

        UsersAPI usersAPI = new UsersAPI(this, MyConstants.APP_KEY, accessToken);
        final Long mUid = Long.parseLong(accessToken.getUid());
        usersAPI.getUserInfo(queue, String.valueOf(mUid), accessToken.getToken(), new UsersAPI.UserInfoListener() {
            @Override
            public void onError() {
                MyToast.show(SinaFriendsActivity.this, getString(R.string.author_fail));
            }

            @Override
            public void onComplete(String result) {
                try {
                    JSONObject json = new JSONObject(result);
                    String sinaName = json.getString("name");
                    String etime = String.valueOf(accessToken.getExpiresTime() / 1000);
                    String token = accessToken.getToken();
                    bindSinaServer(String.valueOf(mUid), sinaName, etime, token);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void bindSinaServer(String mUid, String name, String etime, String token) {
        List<BcyPair> paramsList = new ArrayList<>();
        String url = HttpUtils.BASE_URL + UserApi.getBindSina();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.SINA_PARAM_UID, mUid));
        paramsList.add(new BcyPair(HttpUtils.SINA_PARAM_TOKEN, token));
        paramsList.add(new BcyPair(HttpUtils.SINA_PARAM_NAME, name));
        paramsList.add(new BcyPair(HttpUtils.SINA_PARAM_ETIME, etime));
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                if (StatusCodeUtils.dealStatusCode(result, getContext())) {
                    initData();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(requestParam);
    }

    private void doweiboAuthor() {

        mSsoHandler.authorize(new WbAuthListener() {
            @Override
            public void onSuccess(Oauth2AccessToken oauth2AccessToken) {
                try {
                    bindSina(oauth2AccessToken);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void cancel() {

            }

            @Override
            public void onFailure(WbConnectErrorMessage wbConnectErrorMessage) {

            }

        });
    }


    private void dealJson(List<SinaUser> temp) {
        if (page == 0) {
            slist.clear();
        }
        slist.addAll(temp);
        if (null != adapter) {
            adapter.notifyDataSetChanged();
        } else {
            adapter = new SinaFriendAdapter(SinaFriendsActivity.this, slist);
            mListView.setAdapter(adapter);
        }
        is_load = false;
        mProgressbarHelper.onSuccess();
        refreshListView.onRefreshComplete();
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initAction() {
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                offset = 0;
                page = 0;
                isEnd = false;
                is_load = false;
                initData();
            }
        });

        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!isEnd && !is_load) {
                    page++;
                    initData();
                }
            }
        });
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.sina_friend));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
}
